package com.evriko.commenterall.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * @author Volodymyr.Petrusha vladimir.petrusha@gmail.com
 * @version $Id CommonFilter.java 13:53:01
 */
/**
 * @author Volodymyr.Petrusha
 *
 */
public class CommonFilter implements Filter {

	protected static final String DEFAULT_PAGE_TITLE = "Review All Things";
	
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        if (user != null) {
        	request.setAttribute("currentUserName", user.getNickname());
        } else {
        	request.setAttribute("loginUrl", userService.createLoginURL(
        			((HttpServletRequest)request).getRequestURI()));       	
        	request.setAttribute("currentUserName", null);
        }
		request.setAttribute("_TITLE_", getPageTitle());
		chain.doFilter(request, response);
	}

	private String getPageTitle() {
		// TODO Implement me
		
		return DEFAULT_PAGE_TITLE;
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}

}
